﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Flagwind.Plugins
{
	public class PluginElementPropertyCollection : KeyedCollection<string, PluginElementProperty>
	{
		#region 成员字段

		private PluginElement _owner;

		#endregion

		#region 构造方法

		public PluginElementPropertyCollection(PluginElement owner) : base(StringComparer.OrdinalIgnoreCase)
		{
			if(owner == null)
				throw new ArgumentNullException(nameof(owner));

			_owner = owner;
		}

		#endregion

		#region 公共方法

		public bool TryGet(string name, out PluginElementProperty value)
		{
			value = null;

			var dictionary = this.Dictionary;

			if(dictionary != null)
				return dictionary.TryGetValue(name, out value);

			foreach(var item in Items)
			{
				if(this.Comparer.Equals(GetKeyForItem(item), name))
				{
					value = item;
					return true;
				}
			}

			return false;
		}

		public bool Set(string name, string rawValue)
		{
			if(string.IsNullOrWhiteSpace(name))
				throw new ArgumentNullException(nameof(name));

			var dictionary = this.Dictionary;

			if(dictionary != null)
			{
				PluginElementProperty property;

				if(dictionary.TryGetValue(name, out property))
				{
					property.RawValue = rawValue;
					return true;
				}
			}

			this.Add(new PluginElementProperty(_owner, name, rawValue));
			return false;
		}

		#endregion

		#region 重写方法

		protected override string GetKeyForItem(PluginElementProperty item)
		{
			return item.Name;
		}

		protected override void InsertItem(int index, PluginElementProperty item)
		{
			if(item == null)
				throw new ArgumentNullException(nameof(item));

			//设置属性的所有者
			item.Owner = _owner;

			//调用基类同名方法
			base.InsertItem(index, item);
		}

		#endregion
	}
}